package com.lee.common.observer

import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ActivityUtils
import com.lee.common.R
import com.lee.common.event.MessageEvent
import com.lee.common.event.RESTART_SCAN
import com.lee.common.utils.*
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import org.greenrobot.eventbus.EventBus

class DefaultObserver(val context: Context) : Observer<String> {

    override fun onChanged(show: String) {

        val toLogin = SharedPreUtils.getBoolean("isToLogin", false)

        MaterialDialog.Builder(context)
            .iconRes(R.drawable.icon_tip)
            .title("提示")
            .content(show)
            .cancelable(!toLogin)
            .positiveText("确定")
            .onPositive { _, _ ->
                if (toLogin) login()
                EventBus.getDefault().post(MessageEvent(RESTART_SCAN, show))
            }
            .negativeText("取消")
            .onNegative { _, _ ->
                if (toLogin) login()
                EventBus.getDefault().post(MessageEvent(RESTART_SCAN, show))
            }
            .show()
    }

    fun postMsg(messageEvent: MessageEvent) {

    }

    private fun login() {
        SharedPreUtils.setBoolean("isToLogin", false)
        SharedPreUtils.setBoolean("isLogin", false)
        MyActivityManager.instance.exitApp(context)
        ARouter.getInstance().build(ACTIVITY_LOGIN_NEW)
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
            .navigation(context)
    }

}